import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types/api/user'
import { login, logout, getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(null)
  const refreshTokenValue = ref('')
  const clientId = ref('') // SSO客户端ID
  const user = ref<User | null>(null)
  const permissions = ref<string[]>([])
  const router = useRouter()

  // 添加心跳检测，定期检查token是否有效
  let heartbeatTimer: number

  const startHeartbeat = () => {
    heartbeatTimer = setInterval(async () => {
      try {
        await axios.post('/api/auth/check-token')
      } catch (error) {
        // token失效（可能是在其他地方登录），执行登出操作
        if (error.response?.status === 401) {
          ElMessage.error('您的账号已在其他地方登录')
          await logout()
          router.push('/login')
        }
      }
    }, 30000) // 每30秒检查一次
  }

  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
    }
  }

  // 登录
  async function loginAction(username: string, password: string) {
    const { token: accessToken } = await login(username, password)
    token.value = accessToken
    await getUserInfoAction()
  }

  // SSO登录
  async function ssoLogin(ticket: string) {
    const { token: accessToken } = await validateTicket(ticket)
    token.value = accessToken
    await getUserInfoAction()
  }

  // 获取用户信息
  async function getUserInfoAction() {
    const data = await getUserInfo()
    user.value = data.user
    permissions.value = data.permissions
  }

  // 登出
  async function logoutAction() {
    await logout()
    token.value = null
    user.value = null
    permissions.value = []
  }

  // 检查权限
  function checkPermission(permission: string) {
    return permissions.value.includes(permission)
  }

  // Token自动刷新
  const startTokenRefresh = () => {
    const refreshInterval = setInterval(async () => {
      try {
        const { data } = await axios.post('/api/sso/refresh')
        token.value = data.token
      } catch (error) {
        clearInterval(refreshInterval)
        logout()
      }
    }, 1000 * 60 * 30) // 30分钟刷新一次
  }

  // SSO登出
  const ssoLogout = async () => {
    try {
      await logoutApi(clientId.value)
      token.value = null
      refreshTokenValue.value = ''
      clearUserInfo()
    } catch (error) {
      throw error
    }
  }

  function setToken(newToken: string | null) {
    token.value = newToken
  }

  function logout() {
    token.value = null
  }

  return {
    token,
    refreshTokenValue,
    clientId,
    user,
    permissions,
    loginAction,
    logoutAction,
    checkPermission,
    ssoLogin,
    startTokenRefresh,
    ssoLogout,
    setToken,
    logout
  }
}) 